﻿using Microsoft.Win32;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Security.Policy;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;

namespace XiTi
{
    public partial class MainForm : Form
    {
        Encoding utf8 = new UTF8Encoding(false);
        enum Subject
        {
            语文 = 2, 数学 = 3, 英语 = 4, 物理 = 6, 化学 = 7, 历史 = 8, 道法 = 9, 地理 = 10, 生物 = 11
        }
        public delegate void myDelegate(string str);

        public bool islogin = false;


        private string getListUrl()
        {
            string subject = cb_subject.SelectedItem.ToString();
            Subject s = (Subject)Enum.Parse(typeof(Subject), subject);
            int sid = (int)s;
            return "https://zujuan.21cnjy.com/question?tree_type=knowledge&xd=2&chid=" + sid.ToString();
        }

        public MainForm()
        {
            InitializeComponent();
            WebView2Helper.SetWebView2ExecutableFolder(webView21, "F:\\WebView2");
            webView21.EnsureCoreWebView2Async();
            PaperManagerHelper.Take();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            cb_subject.Items.Clear();
            string[] subjects = Enum.GetNames(typeof(Subject));
            foreach (string subject in subjects)
                cb_subject.Items.Add(subject);
            cb_subject.SelectedItem = getSubject();

            cb_exam.Items.AddRange(PaperManagerHelper.Take().getPaperList().ToArray());
            if (cb_exam.Items.Count > 0)
                cb_exam.SelectedIndex = 0;
        }

        private void bt_back_Click(object sender, EventArgs e)
        {
            if (webView21.CanGoBack) webView21.GoBack();
        }

        private void bt_forword_Click(object sender, EventArgs e)
        {
            if (webView21.CanGoForward) webView21.GoForward();
        }

        private void bt_浏览_Click(object sender, EventArgs e)
        {
            webView21.Source = new Uri(getListUrl());
        }

        private void bt_登录_Click(object sender, EventArgs e)
        {
            webView21.Source = new Uri("https://passport.21cnjy.com/login?jump_url=https%3A%2F%2Fzujuan.21cnjy.com%2Fu%2Fzujuan");
        }

        private void cb_subject_SelectedIndexChanged(object sender, EventArgs e)
        {
            string subject = cb_subject.SelectedItem.ToString();
            if (!getSubject().Equals(subject))
            {
                File.WriteAllText("subject.txt", subject, utf8);
                lb_msg.Text = "更改学科为：" + subject;
            }
        }

        private string getSubject()
        {
            if (File.Exists("subject.txt"))
            {
                return File.ReadAllText("subject.txt", utf8);
            }
            else
            {
                return "物理";
            }
        }

        private void bt_downTest_Click(object sender, EventArgs e)
        {
            if (cb_exam.SelectedItem != null)
            {
                PaperItem item = (PaperItem)cb_exam.SelectedItem;

                string json = File.ReadAllText(PaperManagerHelper.Take().getPaperJsonFile(item.id), PaperManagerHelper.utf8);

                var paper = JsonConvert.DeserializeObject<Paper>(json);
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "Html (*.html)|*.html";
                sfd.DefaultExt = "html";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    File.WriteAllText(sfd.FileName, paper.TakeHtml(), PaperManagerHelper.utf8);
                    File.WriteAllText(sfd.FileName+".answer.html", paper.TakeAnswerHtml(), PaperManagerHelper.utf8);
                    lb_msg.Text = "试卷下载完成";
                }
            }
        }

        private async Task<Paper> GetPaperAsync()
        {
            object obj = await webView21.CoreWebView2.ExecuteScriptAsync("document.body.innerHTML");
            string html = Regex.Unescape(obj.ToString());  //downhtml(browser.Url);
            Regex jre = new Regex("paper_detail: (.*?),\n");
            Match jmc = jre.Match(html);
            if (jmc.Success)
            {
                var json = jmc.Groups[1].Value;
                var paper = JsonConvert.DeserializeObject<Paper>(json);
                return paper;
            }
            return null;
        }

        private async void bt_exam_Click(object sender, EventArgs e)
        {
            if (webView21.Source.AbsoluteUri.StartsWith("https://zujuan.21cnjy.com/paper/view/"))//后面是paperid
            {
                var paper = await GetPaperAsync();
                if (paper != null)
                {
                    PaperItem item = PaperManagerHelper.Take().savePaper(paper);
                    if (item != null)
                    {
                        cb_exam.Items.Add(item);
                        cb_exam.SelectedIndex = cb_exam.Items.Count - 1;
                        lb_msg.Text = "下载完成";
                    }
                }
            }
            else
            {
                lb_msg.Text = "打开试卷后，再点下载。";
            }

        }

        private async void Bt_downAnswer(object sender, EventArgs e)
        {
            if (cb_exam.SelectedItem != null)
            {
                PaperItem item = (PaperItem)cb_exam.SelectedItem;

                string json = File.ReadAllText(PaperManagerHelper.Take().getPaperJsonFile(item.id), PaperManagerHelper.utf8);
                var paper = JsonConvert.DeserializeObject<Paper>(json);

                long t = DateTime.Now.Ticks;
                //AnswerORC orc = new AnswerORC();
                //WebClient w = new WebClient();
                await webView21.ExecuteScriptAsync("var script = document.createElement(\"script\");script.type = \"text/javascript\";script.text = \"function downAnswer(url){let xmlhttp=new XMLHttpRequest();xmlhttp.open('GET',url,false);xmlhttp.send();return xmlhttp.responseText;}\";document.body.appendChild(script);");

                lb_msg.Text = "开始下载答案，共" + paper.content.Count.ToString();

                foreach (var content in paper.content)
                {
                    List<Question> qq = content.questions;
                    foreach (var q in qq)
                    {
                        if (q.qa != null && q.qa.data!=null)
                            continue;
                        //https://zujuan.21cnjy.com/api/question/question-detail-access?qid=52876855&_=1669969959765
                        string url = "https://zujuan.21cnjy.com/api/question/question-detail-access?qid=" + q.question_id.ToString() + "&_=" + t.ToString();
                        object obj = await webView21.CoreWebView2.ExecuteScriptAsync("downAnswer('" + url + "')");
                        string anawer = Regex.Unescape(obj.ToString()).Trim('"');  //downhtml(browser.Url);
                        t++;

                        var a = JsonConvert.DeserializeObject<Answer>(anawer);
                        q.qa = a;
                        /*
                        if (a.data != null)
                        {
                            byte[] d = w.DownloadData(a.data.answer);
                            MemoryStream ms = new MemoryStream(d);
                            Bitmap bmp = new Bitmap(ms);
                            q.qa = orc.orc(bmp);
                        }
                        else
                        {
                            Console.WriteLine(url);
                        }
                        */
                        File.WriteAllText(PaperManagerHelper.Take().getPaperJsonFile(item.id), JsonConvert.SerializeObject(paper), utf8);
                    }
                }
                lb_msg.Text = "答案下载完成";
            }
        }

        private void bt_del_Click(object sender, EventArgs e)
        {
            if (cb_exam.SelectedItem != null)
            {
                PaperItem item = (PaperItem)cb_exam.SelectedItem;
                cb_exam.Items.Remove(item);
                PaperManagerHelper.Take().deletePaper(item);
            }
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            //server.stop();
        }

        private void bt_mryt_Click(object sender, EventArgs e)
        {
            new MRYTForm(cb_subject.SelectedItem.ToString()).Show();
        }

        private void webView21_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e)
        {
            webView21.Source = new Uri(getListUrl());
            webView21.CoreWebView2.NewWindowRequested += CoreWebView2_NewWindowRequested;
        }

        private void CoreWebView2_NewWindowRequested(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NewWindowRequestedEventArgs e)
        {
            e.NewWindow = webView21.CoreWebView2;
        }

        private void webView21_NavigationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e)
        {
            webView21.ExecuteScriptAsync("var items=document.getElementsByTagName('a');var len=items.length;for(var i=0;i<len;i++){items[i].target='_self';}");
            if (webView21.Source.AbsoluteUri.StartsWith("https://passport.21cnjy.com/login?"))
            {
                //document.getElementsByTagName('button')[0].click();
                webView21.ExecuteScriptAsync("document.getElementsByName('LoginForm[username]')[0].value='15938101172';document.getElementsByName('LoginForm[password]')[0].value='ks45i89';");
            }
            lb_msg.Text = webView21.Source.AbsoluteUri;
        }


        private async Task<Question> GetDetailAsync()
        {
            object obj = await webView21.CoreWebView2.ExecuteScriptAsync("document.body.innerHTML");
            string html = Regex.Unescape(obj.ToString());  //downhtml(browser.Url);
            Regex jre = new Regex(" question: (.*?)\n");
            Match jmc = jre.Match(html);
            if (jmc.Success)
            {
                string fullhtml = jmc.Groups[1].Value;
                var result = JsonConvert.DeserializeObject<Question>(fullhtml);
                return result;
            }
            return null;
        }

        private async void bt_questions_Click(object sender, EventArgs e)
        {
            string url = webView21.Source.AbsoluteUri;
            List<Question> qlist = new List<Question>();
            if (webView21.Source.AbsoluteUri.StartsWith("https://zujuan.21cnjy.com/paper/view/"))//后面是paperid
            {
                var paper = await GetPaperAsync();
                if (paper != null)
                {
                    foreach(var cnt in paper.content)
                    {
                        qlist.AddRange(cnt.questions);
                    }
                }
            }
            else if (url.StartsWith("https://zujuan.21cnjy.com/question/detail"))
            {
                var q = await GetDetailAsync();
                if (q != null)
                {
                    qlist.Add(q);
                }
            }
            else
            {
                lb_msg.Text = "打开试卷或习题，再点讲解。";
            }
            if (qlist.Count > 0)
            {
                this.BeginInvoke(new ShowQuestionFormDelegate(ShowQuestionForm), qlist);

            }
            else
            {
                lb_msg.Text = "获取习题失败。";
            }
        }

        delegate void ShowQuestionFormDelegate(List<Question> qlist);

        private void ShowQuestionForm(List<Question> qlist)
        {
            QutstionForm qf = new QutstionForm(qlist);
            qf.ShowDialog();
        }

        private async void bt_pub_Click(object sender, EventArgs e)
        {
            string url = webView21.Source.AbsoluteUri;
            if (url.StartsWith("https://zujuan.21cnjy.com/question/detail"))
            {
                var q = await GetDetailAsync();
                if (q != null)
                {
                    lb_msg.Text = "添加习题";

                    string s = JsonHelper.question2Html(q);
                    string publish_date = DateTime.Now.ToString("yyyy-MM-dd");
                    var d = new DataItem();
                    d.title = publish_date;
                    d.km = (string)cb_subject.SelectedItem;
                    d.html = s;
                    d.fullhtml = "";

                    string msg;
                    int id = ApiHelper.indset(d, out msg);
                    if (id > 0)
                    {
                        d.id = id;
                    }
                    else
                    {
                        lb_msg.Text = msg;
                    }
                }
            }
            else
            {
                lb_msg.Text = "打开试卷或习题，再点讲解。";
            }
        }
    }
}
